/**
 * 拖拽控件
 * 场景：任务管理-任务详情-通话记录-定制列
 *
 * @author wujianx
 * @createDate 2020-10-25
 */
import React from 'react';
import { JSONObject } from 'admin/schema/common';
import './style.scss';

export interface DragItem {
  data: JSONObject;
  render: (data: JSONObject, index: number) => JSX.Element;
}
export interface DragListProp {
  /**行-集合 */
  items: DragItem[];
}

export interface DragListState extends DragListProp {}

/**
 * 拖拽控件
 */
export class DragList extends React.Component<DragListProp, DragListState> {
  private draggingItem: any;

  private dragOverItem: any;

  constructor(prop: DragListProp) {
    super(prop);
    this.draggingItem = {};
    this.dragOverItem = {};
    this.state = {
      ...prop,
    };
  }

  public setValue(prop: DragListProp): void {
    this.setState({
      items: prop.items,
    });
  }

  private handleDragStart(e: React.DragEvent<HTMLHeadingElement>, index: number): void {
    this.draggingItem.current = index;
  }

  private handleDragEnter(e: React.DragEvent<HTMLHeadingElement>, index: number): void {
    const listCopy = [...this.state.items];
    const draggingItem = this.draggingItem;
    const draggingIndex = draggingItem.current;
    this.dragOverItem.current = index;
    const item = listCopy[draggingIndex];
    listCopy.splice(draggingIndex, 1);
    listCopy.splice(index, 0, item);
    this.setState({
      items: listCopy,
    });
  }

  public getValue() {
    return this.state.items;
  }

  render() {
    const { items } = this.state;

    return (
      <>
        {items.map((item, index) => {
          return (
            <div
              key={index}
              draggable
              onDragStart={(e: React.DragEvent<HTMLHeadingElement>) =>
                this.handleDragStart(e, index)
              }
              onDragOver={(e: React.DragEvent<HTMLHeadingElement>) => e.preventDefault()}
              onDrop={(e: React.DragEvent<HTMLHeadingElement>) => this.handleDragEnter(e, index)}
            >
              {item.render(item.data, index)}
            </div>
          );
        })}
      </>
    );
  }
}

/**
 * dragList测试集
 */
export const DragListTest = () => {
  const domBuilder = () => {
    return (data: JSONObject, index: number) => {
      return (
        <>
          <span>{index}</span>
          <span style={{ marginLeft: '15px' }}>{data.name}</span>
        </>
      );
    };
  };

  const data = [
    {
      data: {
        name: 'wujianx',
      },
      render: domBuilder(),
    },
    {
      data: {
        name: 'wangluh',
      },
      render: domBuilder(),
    },
    {
      data: {
        name: 'kejint',
      },
      render: domBuilder(),
    },
    {
      data: {
        name: 'maojianw',
      },
      render: domBuilder(),
    },
    {
      data: {
        name: 'yanhand',
      },
      render: domBuilder(),
    },
  ];

  return <DragList items={data} />;
};
